<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="选择店铺：" prop="storeId">
        <el-select v-model="queryParams.storeId" placeholder="请选择店铺" filterable>
          <el-option v-for="(item,index) in storeList" :key="index"
                     :label="item.storeUserName + ' - ' + item.storeName"
                     :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分组名" prop="groupName">
        <el-input
          v-model="queryParams.groupName"
          placeholder="请输入分组名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备注" prop="memo">
        <el-input
          v-model="queryParams.memo"
          placeholder="请输入备注"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="速卖通分组id" prop="groupId">
        <el-input
          v-model="queryParams.groupId"
          placeholder="请输入速卖通分组id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上级" prop="parentId">
        <el-input
          v-model="queryParams.parentId"
          placeholder="请输入上级"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-download" size="mini" @click="handleSync">同步</el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="danger"-->
      <!--          plain-->
      <!--          icon="el-icon-delete"-->
      <!--          size="mini"-->
      <!--          :disabled="multiple"-->
      <!--          @click="handleDelete"-->
      <!--        >删除-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          plain-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['gather:sellerStoreGroup:export']"-->
      <!--        >导出-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="sellerStoreGroupList" @selection-change="handleSelectionChange"
              default-expand-all row-key="id" stripe border :tree-props="{children: 'childGroup'}">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="分组名" align="center" prop="groupName"/>
      <el-table-column label="分组id" align="center" prop="groupId"/>
      <!--      <el-table-column label="上级" align="center" prop="parentId"/>-->
      <el-table-column label="商品数量" align="center" prop="productCount"/>
      <!--      <el-table-column label="同步状态" align="center" prop="synchronizationStatus">-->
      <!--        <template slot-scope="scope">-->
      <!--          <div>{{ scope.row.synchronizationStatus == '1' ? '已同步' : '未同步' }}</div>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="店铺id" align="center" prop="storeId"/>-->
      <el-table-column label="备注" align="center" prop="memo"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <div v-if="scope.row.childGroup">
            <div v-if="scope.row.childGroup.length<1">
              <el-button size="mini" type="text" @click="chooseProduct(scope.row)">
                选择产品
              </el-button>
              <el-button size="mini" type="text" @click="syncProduct(scope.row)">同步</el-button>
              <el-button size="mini" type="text" @click="openSetMarkModal(scope.row)">修改备注</el-button>
            </div>
            <!--            <el-button size="mini" type="text" @click="handleUpdate(scope.row)">增加二级分组</el-button>-->
          </div>
          <div v-else>
            <el-button size="mini" type="text" @click="chooseProduct(scope.row)">选择产品</el-button>
            <el-button size="mini" type="text" @click="syncProduct(scope.row)">同步</el-button>
            <el-button size="mini" type="text" @click="openSetMarkModal(scope.row)">修改备注</el-button>

          </div>
          <!--          <el-button size="mini" type="text" @click="handleUpdate(scope.row)">修改</el-button>-->
          <!--          <el-button size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户店铺商品分组对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="店铺id" prop="storeId">
          <el-select v-model="form.storeId" placeholder="请选择店铺" filterable>
            <el-option v-for="(item,index) in storeList" :key="index"
                       :label="item.storeUserName + ' - ' + item.storeName"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分组名" prop="groupName">
          <el-input v-model="form.groupName" placeholder="请输入分组名"/>
        </el-form-item>
        <el-form-item label="上级" prop="parentId">
          <el-select v-model="form.parentId" placeholder="请选择上级分组名称" filterable>
            <el-option v-for="(item,index) in groupIdList" :key="index"
                       :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
          <!--          <el-input v-model="form.parentId" placeholder="请输入上级"/>-->
        </el-form-item>
        <el-form-item label="备注" prop="memo">
          <el-input v-model="form.memo" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 在线商品列表 -->
    <GroupProductList v-if="isOpenChooseProductModal" :storeId="storeId" :groupId="groupId"
                      @close="closeIsImport"/>
  </div>
</template>

<script>
import {
  listSellerStoreGroup,
  getSellerStoreGroup,
  delSellerStoreGroup,
  addSellerStoreGroup,
  updateSellerStoreGroup, synchronizeProductGroup, queryStoreGroupList, setMemo
} from "@/api/product/online/productGroup";
import {getStoreInfo} from "@/api/order/orderApi";
import dialogList from "@/views/persongather/components/dialogList.vue";
import GroupProductList from "@/views/product/components/GroupProductList.vue";

export default {
  name: "SellerStoreGroup",
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户店铺商品分组表格数据
      sellerStoreGroupList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        groupName: undefined,
        memo: undefined,
        groupId: undefined,
        parentId: undefined,
        synchronizationStatus: undefined,
        status: undefined,
        storeId: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        groupName: [{required: true, message: "分组名不能为空", trigger: "blur"}],
        memo: [{required: false, message: "备注不能为空", trigger: "blur"}],
        groupId: [{required: true, message: "速卖通分组id不能为空", trigger: "blur"}],
        parentId: [{required: true, message: "上级不能为空", trigger: "blur"}],
        storeId: [{required: true, message: "店铺id不能为空", trigger: "blur"}],
      },
      storeList: [],//店铺列表
      isOpenChooseProductModal: false,//是否打开选择产品组件
      pubLoading: false,//选择产品组件loading
      groupId: "",//选择的分组id
      groupIdList: [],//分组id列表
      storeId: "",//店铺id
    };
  },
  components: {
    dialogList,
    GroupProductList
  },
  created() {
    this.getList();
    this.getStoreList()
  },
  methods: {
    // 同步
    handleSync() {
      const storeId = this.queryParams.storeId
      if (storeId) {
        this.$modal.confirm('是否确定从速卖通同步该店铺内商品分组？').then(() => {
          const params = {
            storeId: storeId
          }
          queryStoreGroupList(params).then(res => {
            this.$modal.msgSuccess(res.msg);
            this.getList();
          })
        })
      } else {
        this.$modal.msgError("请先选择店铺！");
      }
    },
    // 关闭导入弹窗
    closeIsImport() {
      this.getList()
      this.isOpenChooseProductModal = false;
      // this.$refs.queryForm
    },
    //  获取店铺列表
    getStoreList() {
      this.loading = true
      getStoreInfo().then(response => {
        this.storeList = response
      })
    },
    /** 查询用户店铺商品分组列表 */
    getList() {
      this.loading = true;
      listSellerStoreGroup(this.queryParams).then(response => {
        let list = response.rows
        this.sellerStoreGroupList = list;
        this.groupIdList = [{
          label: '一级分组（无上级时选此项）',
          value: 0
        }]
        for (let i = 0; i < list.length; i++) {
          this.groupIdList.push({
            label: list[i].groupName,
            value: list[i].groupId
          })
        }
        console.log('this.groupIdList', this.groupIdList)
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        groupName: undefined,
        memo: undefined,
        groupId: undefined,
        parentId: undefined,
        synchronizationStatus: undefined,
        status: undefined,
        storeId: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户店铺商品分组";
    },
    // 选择产品
    chooseProduct(row) {
      console.log('选择产品row', row)
      this.groupId = row.groupId
      this.storeId = row.storeId
      this.isOpenChooseProductModal = true
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getSellerStoreGroup(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改用户店铺商品分组";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateSellerStoreGroup(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addSellerStoreGroup(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    // 设置备注
    openSetMarkModal(row) {
      let inputValue = row.memo ? row.memo : ''
      this.$prompt('请输入备注', '提示', {
        // inputPattern: /^.+$/,
        // inputErrorMessage: '请输入备注内容',
        inputValue: inputValue
      }).then((value) => {
        if (value) {
          let data = {
            id: row.id,
            memo: value.value
          }
          setMemo(data).then(res => {
            this.$message.success(res.msg)
            this.getList()
          })
        }
      })
    },
    // 同步分组内商品
    syncProduct(row) {
      this.$modal.confirm('是否确认同步分组名为"' + row.groupName + '"内的商品？').then(() => {
        synchronizeProductGroup({groupId: row.groupId}).then(res => {
          this.$message.success(res.msg)
          this.getList()
        })
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除用户店铺商品分组编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delSellerStoreGroup(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('gather/gather/sellerStoreGroup/export', {
        ...this.queryParams
      }, `sellerStoreGroup_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
